package com.cytangaa.display;


import java.text.SimpleDateFormat;
import java.util.Date;

import com.cytanaa.youlike.Preferences;
import com.cytanaa.youlike.R;
import com.cytangaa.displaysize.DisplaySize;
import com.cytangaa.youlike.database.DbAdapter;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.RelativeLayout.LayoutParams;

public class Player extends Activity {
	private static final String fb_id = "416965195026704";
	private SharedPreferences mPrefs;
	DisplaySize mDisplaySize;
	String SrcPath1 = "rtsp://v1.cache5.c.youtube.com/CiILENy73wIaGQkgHx9w8aRdHhMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp";
	String youtubeLink = null;
	String thumbnailLink, description, VideoId, viewCount, date = null;
	String title = null;
	String duration = null;
	private MediaController mMediaController;
	protected TextView titlebar_title;
	protected ImageView titlebar_icon;
	public Button basket_btn, share_btn;
	public static final String likeLink2 = "http://www.facebook.com/YouLikePage";
	public static final String photoLink = "http://www.freeimagehosting.net/t/fi8ps.jpg";
	// Handling database
	DbAdapter db;

	private Facebook facebook = new Facebook(fb_id);;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		super.onCreate(savedInstanceState);
		
		getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
		LayoutInflater inflator = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		View v = inflator.inflate(R.layout.recommended_title, null);
		this.getActionBar().setDisplayShowCustomEnabled(true);
		this.getActionBar().setDisplayShowTitleEnabled(false);
		this.getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffff0000")));
		this.getActionBar().setCustomView(v);        
		setContentView(R.layout.player_vertical);


		db = new DbAdapter(this);

		//titlebar_title.setText("Playing");
		//titlebar_icon.setImageResource(R.drawable.titlebar_play);
		Bundle bundle = this.getIntent().getExtras();
		SrcPath1 = bundle.getString("link");
		youtubeLink = bundle.getString("youtubeLink");
		thumbnailLink = bundle.getString("thumbnailLink");
		// description = bundle.getString("description");
		title = bundle.getString("title");
		VideoId = bundle.getString("id");
		duration = bundle.getString("duration");
		viewCount = bundle.getString("view_count");
		date = bundle.getString("uploaded_date");
		Log.v("duration", "duration is " + duration);
		Log.v("viewCount", "viewCount is " + viewCount);
		Log.v("VideoId", "VideoId is " + VideoId);
		mPrefs = getSharedPreferences("facebook_session", MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);
		Log.i("postToWall",
				"facebook.setAccessToken(access_token), and access_token=="
						+ access_token);
		if (access_token != null) {
			facebook.setAccessToken(access_token);
			Log.i("postToWall",
					"facebook.setAccessToken(access_token), and facebook.isSessionValid()=="
							+ facebook.isSessionValid());
		}
		if (expires != 0) {
			facebook.setAccessExpires(expires);
			Log.i("postToWall", "facebook.setAccessExpires(expires)" + expires);
		}
		
		setAutoOrientationEnabled(this.getContentResolver(), true);
		
		/*
		 * code for initializing the layout
		 */
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int heightPix = displaymetrics.heightPixels;
		int widthPix = displaymetrics.widthPixels;
				
		mDisplaySize = new DisplaySize(this);
		Display display = getWindowManager().getDefaultDisplay();
		int[] widthHeight = new int[2];
		widthHeight = mDisplaySize.getDisplaySize(display);
		int width = widthHeight[0];

		VideoView myVideoView = (VideoView) findViewById(R.id.my_videoview);
		LayoutParams lp = new RelativeLayout.LayoutParams(width,
				(width / 4) * 3);
		lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		myVideoView.setLayoutParams(lp);
		
		share_btn = (Button)findViewById(R.id.share_btn);
		RelativeLayout.LayoutParams layoutParams  = new    
				RelativeLayout.LayoutParams(widthPix/2, heightPix/7);
		layoutParams.addRule(RelativeLayout.BELOW, R.id.my_videoview);
		share_btn.setLayoutParams(layoutParams);
		
		basket_btn = (Button)findViewById(R.id.basket_btn);
		RelativeLayout.LayoutParams layoutParams2  = new    
				RelativeLayout.LayoutParams(widthPix/2, heightPix/7);
		layoutParams2.addRule(RelativeLayout.RIGHT_OF, R.id.share_btn);
		layoutParams2.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.share_btn);
		basket_btn.setLayoutParams(layoutParams2);

		mMediaController = new MediaController(this);
		// mMediaController =
		// (MediaController)findViewById(R.id.mediaController);
		// mMediaController.setAnchorView(myVideoView);
		mMediaController.setPadding(0, 0, 0, (width / 4) * 3 + width / 10);
		myVideoView.setVideoURI(Uri.parse(SrcPath1));
		myVideoView.setMediaController(mMediaController);
		myVideoView.requestFocus();
		myVideoView.start();

	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		Log.i("onConfigurationChanged", "changed");
		// Checks the orientation of the screen
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			Display display = getWindowManager().getDefaultDisplay();
			int[] widthHeight = new int[2];
			widthHeight = mDisplaySize.getDisplaySize(display);
			int height = widthHeight[1];

			VideoView myVideoView = (VideoView) findViewById(R.id.my_videoview);
			LayoutParams lp = new RelativeLayout.LayoutParams(height*4/3, height);
			lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
			//lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			//lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
			lp.addRule(RelativeLayout.CENTER_VERTICAL);
			lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
			if (myVideoView.isPlaying()) {
				myVideoView.stopPlayback();
				myVideoView.clearFocus();
			}
			//TODO
			//getWindow().requestFeature(Window.FEATURE_NO_TITLE);
			ActionBar actionBar = getActionBar();
			actionBar.hide();
			setContentView(R.layout.player_horizontal);
			myVideoView = (VideoView) findViewById(R.id.my_videoview_horizontal);

			// View b = findViewById(R.id.share_btn);
			// b.setVisibility(View.GONE);
			myVideoView.setLayoutParams(lp);
			mMediaController.setPadding(0, 0, 0, 0);
			myVideoView.setVideoURI(Uri.parse(SrcPath1));
			myVideoView.setMediaController(mMediaController);
			myVideoView.requestFocus();
			myVideoView.start();
			Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			ActionBar actionBar = getActionBar();
		    actionBar.show();
			LayoutInflater inflator = (LayoutInflater) this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View v = inflator.inflate(R.layout.recommended_title, null);
			this.getActionBar().setDisplayShowCustomEnabled(true);
			this.getActionBar().setDisplayShowTitleEnabled(false);
			this.getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffff0000")));
			this.getActionBar().setCustomView(v); 
			Display display = getWindowManager().getDefaultDisplay();
			int[] widthHeight = new int[2];
			widthHeight = mDisplaySize.getDisplaySize(display);
			int width = widthHeight[0];
			VideoView myVideoView = (VideoView) findViewById(R.id.my_videoview_horizontal);
			/**
			 * initializing layout again when the View is recreate
			 */
			
			DisplayMetrics displaymetrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
			int heightPix = displaymetrics.heightPixels;
			int widthPix = displaymetrics.widthPixels;
			LayoutParams lp = new RelativeLayout.LayoutParams(width,
					(width / 4) * 3);
			lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
			lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

			if (myVideoView.isPlaying()) {
				myVideoView.stopPlayback();
				myVideoView.clearFocus();
			}
			setContentView(R.layout.player_vertical);
			myVideoView = (VideoView) findViewById(R.id.my_videoview);
			share_btn = (Button)findViewById(R.id.share_btn);
			RelativeLayout.LayoutParams layoutParams  = new    
					RelativeLayout.LayoutParams(widthPix/2, heightPix/5);
			layoutParams.addRule(RelativeLayout.BELOW, R.id.my_videoview);
			share_btn.setLayoutParams(layoutParams);
			
			basket_btn = (Button)findViewById(R.id.basket_btn);
			RelativeLayout.LayoutParams layoutParams2  = new    
					RelativeLayout.LayoutParams(widthPix/2, heightPix/5);
			layoutParams2.addRule(RelativeLayout.RIGHT_OF, R.id.share_btn);
			layoutParams2.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.share_btn);
			basket_btn.setLayoutParams(layoutParams2);

			// View b = findViewById(R.id.share_btn);
			// b.setVisibility(View.GONE);
			myVideoView.setLayoutParams(lp);
			mMediaController.setPadding(0, 0, 0, (width / 4) * 3 + width / 10);
			myVideoView.setVideoURI(Uri.parse(SrcPath1));
			myVideoView.setMediaController(mMediaController);
			myVideoView.requestFocus();
			myVideoView.start();

		}
	}

	public class MyVideoView extends VideoView {

		public MyVideoView(Context context) {
			super(context);
		}

		@Override
		protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
			// int width = getDefaultSize(0, widthMeasureSpec);
			// int height = getDefaultSize(0, heightMeasureSpec);
			// setMeasuredDimension(width , height);
		}

	}

	public void Share(View v) {
		postToWall();
	}

	public void WatchLater(View v) {
		db.open();

		Cursor cursor = db.getTitle(VideoId);
		Log.i("checking", "checking duration : " + duration);

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Log.i("checking", "checking checking 1");
		Date addDate = new Date();
		Log.i("checking", "checking checking 1");
		String mdate = dateFormat.format(addDate);
		if (cursor.moveToFirst()) {
			Log.i("checking", "checking update 1");
			// boolean dbResult=db.updateTitle(VideoId, date, "nil", title,
			// thumbnailLink, duration, youtubeLink,
			// SrcPath1, viewCount, addDate);
			Toast.makeText(this, "Added Before", Toast.LENGTH_SHORT).show();

		} else {
			Log.i("checking", "checking create 1");
			Log.i("checking", "checking date 1" + date);
			Log.i("checking", "checking VideoId 1" + VideoId);
			Log.i("checking", "checking title 1" + title);
			Log.i("checking", "checking thumbnailLink 1" + thumbnailLink);
			Log.i("checking", "checking duration 1" + duration);
			Log.i("checking", "checking SrcPath1 1" + SrcPath1);
			Log.i("checking", "checking viewCount 1" + viewCount);
			Log.i("checking", "checking mdate 1" + mdate);

			long dbResult = db.insertVideo(date, VideoId, "nil", title,
					thumbnailLink, duration, youtubeLink, SrcPath1, viewCount,
					mdate);
			Log.i("checking", "checking checking Long" + dbResult);
			Toast.makeText(this, "Added Successfully", Toast.LENGTH_SHORT)
					.show();

		}

		db.close();

	}

	/**
	 * Facebook sharing handler
	 */
	public void postToWall() {
		Bundle parameters = new Bundle();
		if (youtubeLink == null) {
			youtubeLink = SrcPath1;
		}
		Log.i("postToWall", "youtubeLink == " + youtubeLink);

		parameters.putString("message", "");
		parameters.putString("link", youtubeLink);
		parameters.putString("description", description);
		parameters.putString("picture", thumbnailLink);

		if (facebook.isSessionValid()) {
			Log.i("postToWall", "mFacebook.isSessionValid()");
			// post on user's wall.
			// feed
			// stream.publish
			// AsyncFacebookRunner mAsyncRunner = new
			// AsyncFacebookRunner(facebook);

			// mAsyncRunner.request("me/feed", parameters, "POST", new
			// FacebookPostListener(), null);

			facebook.dialog(this, "feed", parameters, new DialogListener() {
				@Override
				public void onFacebookError(FacebookError e) {
					Log.i("onFacebookError", "youtubeLink == " + e);

				}

				@Override
				public void onError(DialogError e) {
					Log.i("onFacebookError", "onCancel == " + e);

				}

				@Override
				public void onComplete(Bundle values) {
				}

				@Override
				public void onCancel() {

				}
			});

		} else {
			Log.i("postToWall", "mFacebook.isSessionValid() is not true");
			Log.i("postToWall",
					"mFacebook.getAccessToken(): " + facebook.getAccessToken());

			facebook.authorize(this,
					new String[] { "email", "publish_stream" },
					new DialogListener() {

						@Override
						public void onCancel() {
							// Function to handle cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							// Function to handle complete event
							// Edit Preferences and update facebook acess_token
							SharedPreferences.Editor editor = mPrefs.edit();
							// mFacebook.setAccessToken("tooken");
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
							Log.i("postToWall", "mFacebook.getAccessToken(): "
									+ facebook.getAccessToken());
							Log.i("postToWall",
									"mFacebook.getAccessExpires(): "
											+ facebook.getAccessExpires());
						}

						@Override
						public void onError(DialogError error) {
							// Function to handle error
							Log.i("postToWall", "mFacebook.onError(): " + error);

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Function to handle Facebook errors
							Log.i("postToWall", "mFacebook.onFacebookError(): "
									+ fberror);
						}

					});
		}
	}

	public static void setAutoOrientationEnabled(ContentResolver resolver,
			boolean enabled) {
		Settings.System.putInt(resolver,
				Settings.System.ACCELEROMETER_ROTATION, enabled ? 1 : 0);
	}
	
	@Override
	public void onPause() {
		super.onPause();
		setAutoOrientationEnabled(this.getContentResolver(), false) ;
		
	}
	//TODO
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {

			menu.add(Menu.NONE, Menu.FIRST + 1, 5, "Setting").setIcon(
					android.R.drawable.ic_menu_preferences);
			menu.add(Menu.NONE, Menu.FIRST + 2, 5, "Like us on Facebook").setIcon(
					R.drawable.like_menu);
			menu.add(Menu.NONE, Menu.FIRST + 3, 5, "Share the fun").setIcon(
					R.drawable.share_menu);

			return true;

		}
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {

			switch (item.getItemId()) {
			case Menu.FIRST + 1:
				Intent i = new Intent(this, Preferences.class);
				startActivityForResult(i, 1);

				break;
			case Menu.FIRST + 2:
				// Intent i = new Intent(this, Preferences.class);
				Intent browserIntent2 = new Intent(Intent.ACTION_VIEW,
						Uri.parse(likeLink2));
				startActivity(browserIntent2);
				break;

			case Menu.FIRST + 3:
				// Intent i = new Intent(this, Preferences.class);
				postUsToWall();
				break;
			}
			return false;
		}
		/**
		 * Facebook sharing handler
		 */
		public void postUsToWall() {
			Bundle parameters = new Bundle();

			parameters.putString("message", "");
			parameters.putString("link", likeLink2);
			parameters.putString("description", "Good Stuff!!!!");
			parameters.putString("picture", photoLink);

			if (facebook.isSessionValid()) {
				Log.i("postToWall", "mFacebook.isSessionValid()");
				// mAsyncRunner.request("me/feed", parameters, "POST", new
				// FacebookPostListener(), null);

				facebook.dialog(this, "feed", parameters, new DialogListener() {
					@Override
					public void onFacebookError(FacebookError e) {
						Log.i("onFacebookError", "youtubeLink == " + e);

					}

					@Override
					public void onError(DialogError e) {
						Log.i("onFacebookError", "onCancel == " + e);

					}

					@Override
					public void onComplete(Bundle values) {
					}

					@Override
					public void onCancel() {

					}
				});

			} else {
				Log.i("postToWall", "mFacebook.isSessionValid() is not true");
				Log.i("postToWall",
						"mFacebook.getAccessToken(): " + facebook.getAccessToken());

				facebook.authorize(this,
						new String[] { "email", "publish_stream" },
						new DialogListener() {

							@Override
							public void onCancel() {
								// Function to handle cancel event
							}

							@Override
							public void onComplete(Bundle values) {
								// Function to handle complete event
								// Edit Preferences and update facebook acess_token
								SharedPreferences.Editor editor = mPrefs.edit();
								// mFacebook.setAccessToken("tooken");
								editor.putString("access_token",
										facebook.getAccessToken());
								editor.putLong("access_expires",
										facebook.getAccessExpires());
								editor.commit();
								Log.i("postToWall", "mFacebook.getAccessToken(): "
										+ facebook.getAccessToken());
								Log.i("postToWall",
										"mFacebook.getAccessExpires(): "
												+ facebook.getAccessExpires());
							}

							@Override
							public void onError(DialogError error) {
								// Function to handle error
								Log.i("postToWall", "mFacebook.onError(): " + error);

							}

							@Override
							public void onFacebookError(FacebookError fberror) {
								// Function to handle Facebook errors
								Log.i("postToWall", "mFacebook.onFacebookError(): "
										+ fberror);
							}

						});
			}
		}
}
